import {Pislogin, logout, unlock, getPermissions} from '@/api/user.js'
import {
  setLock,
  getLock,
  removeLock,
  getToken,
  getHasToken,
  setToken,
  setHasToken,
  removeToken,
  setUserInfo,
  getUserInfo,
  removeUserInfo,
  setSysCfgValue,
  getSysValue,
  setIsLogin
} from '@/utils/auth'
import { getApiToken, login ,Logout} from '@/api/login/login'
import { resetRouter }from '@/router'
import qs from 'qs'
import md5 from 'js-md5';
const define = require('@/utils/define')

const state = {
  token: getToken(),
  isLock: getLock() || 0,
  menuList: [],
  leftMenuList: [],
  userInfo: getUserInfo()||{},
  permissionList: [],
  loginLoading: false,
  socket: '',
  hastoken: getHasToken(),
  qx: [],
  baseCodeString: [],
  systemName: getSysValue()||'',
  kc_jky: {}
}

const mutations = {
  SET_JKY_KC: (state, json) => {
    state.kc_jky = json
  },
  SET_SOCKET: (state, socket) => {
    state.socket = socket
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_HAS_TOKEN: (state, token) => {
    state.hastoken = token
  },
  SET_MENULIST: (state, menuList) => {
    state.menuList = menuList
  },
  SET_BASE_CODE_STRING: (state, codeString) => {
    state.baseCodeString = codeString
  },
  SET_QX: (state, menuList) => {
    state.qx = menuList
  },
  SET_LEFTMENULIST: (state, leftMenuList) => {
    state.leftMenuList = leftMenuList
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_SYSCFG_VALUE: (state, systemName) => {
    state.systemName = systemName
  },
  SET_USERINFO_HEADICON: (state, headIcon) => {
    state.userInfo.headIcon = headIcon
  },
  SET_USERINFO_USERNAME: (state, userName) => {
    state.userInfo.userName = userName
  },
  SET_USERINFO_PORTALID: (state, portalId) => {
    state.userInfo.portalId = portalId
  },
  SET_PERMISSION_LIST: (state, permissionList) => {
    state.permissionList = permissionList
  },
  SET_LOCK: (state, isLock) => {
    state.isLock = isLock
  },
  SET_LOGIN_LOADING: (state, loginLoading) => {
    state.loginLoading = loginLoading
  }
}

const actions = {
  // 锁屏
  setLock({ commit }) {
    commit('SET_LOCK', 1)
    setLock(1)
  },
  clearLock({ commit }) {
    commit('SET_LOCK', '')
    removeLock()
  },
  unlock({ dispatch }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      unlock({ account: account.trim(), password: md5(password) }).then(response => {
        dispatch('clearLock')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  token({commit}, app) {
    const { app_key, app_secret } = app
    return new Promise((resolve, reject) => {
      getApiToken({
        app_key: app_key,
        app_secret: app_secret
      }).then(response => {
        commit('SET_TOKEN', response.Response.TokenHead + " " + response.Response.TokenString)
        setToken(response.Response.TokenHead + " " + response.Response.TokenString)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  login({ commit }, userInfo) {
    return new Promise(async (resolve, reject) => {
      await login(userInfo).then(response => {
        const layoutList = ['classic', 'functional', 'plain', 'blend']
        // let layoutType = response.theme && layoutList.indexOf(response.theme) > -1 ? response.theme : 'classic'
        // commit('settings/CHANGE_SETTING', { key: "layoutType", value: layoutType }, { root: true })
        setHasToken(true)
        let user = response.Response
        commit('SET_USERINFO', user)
        setUserInfo(user)
        /*getSysCfgValue( {
          pzmc:"ProductName"
        }).then(res => {
          let sysCfgValue = res.Response
          commit('SET_SYSCFG_VALUE', sysCfgValue)
          setSysCfgValue(sysCfgValue)
        })*/
        resolve(user)
        }).catch(() => {
        reject()
      })
    })
  },
  pislogin({ commit }, userInfo) {
    const { account, password,hospitalname } = userInfo
    return new Promise((resolve, reject) => {
      Pislogin(qs.stringify({
        account: account.trim(),
        password: md5(password),
        hospitalname:hospitalname,
        client_id: account,
        client_secret:  md5(password),
        scope: 'all',
        grant_type: 'password'
      })).then(response => {
        const { data } = response
        const layoutList = ['classic', 'functional', 'plain', 'blend']
        // let layoutType = data.theme && layoutList.indexOf(data.theme) > -1 ? data.theme : 'classic'
        commit('SET_TOKEN', data.token)
        // commit('settings/CHANGE_SETTING', { key: "layoutType", value: layoutType }, { root: true })
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  getInfo({ commit, dispatch }) {
     return new Promise(async (resolve, reject) => {
       await getPermissions().then(response => {
         let yhqx = response.Response
         let menuList = []
         let routerList = []
         let permissionList = []
         for (let i = 0; i < yhqx.length; i++) {
           if (yhqx[i].gnlxdm == '01') {
             let arr = {
               "fullName":yhqx[i].gnmc,
               "enCode": yhqx[i].gndm,
               "icon":yhqx[i].tb,
               "type":yhqx[i].gnlxdm,
               "sortCode":yhqx[i].px,
               "id":yhqx[i].gndm
             }
             menuList.push(arr)
           } else if (yhqx[i].gnlxdm == '02'){
             // 查看当前菜单是否归属一级菜单，确保所有的二级菜单都能找到一级菜单
             setRouterList(menuList, yhqx[i])
           } else {
             setButtonList(permissionList, yhqx[i])
           }
         }
         function getLastStatus (arr) {
           let list = arr.split('.')
           return list[list.length - 1]
         }
         function setButtonList (nodes, item) {
           let bl = false
           for (let i = 0; i < nodes.length; i++) {
             if (nodes[i].modelId === item.sjgndm) {
               nodes[i].button.push({
                 enCode: getLastStatus(item.gndm),
                 fullName: item.gnmc
               })
               bl = true
             }
           }
           if (!bl) {
             let arr = {
               "modelId":item.sjgndm,
               "button":[]
             }
             arr.button.push({
               enCode: getLastStatus(item.gndm),
               fullName: item.gnmc
             })
             nodes.push(arr)
           }
         }
         function setRouterList (nodes, item) {
           nodes.forEach(node => {
             if (node.enCode === item.sjgndm) {
               let arr = {
                 "fullName":item.gnmc,
                 "enCode": item.gndm,
                 "icon":item.tb,
                 "type":item.gnlxdm,
                 "sortCode":item.px,
                 "id":item.gndm
               }
               if (node.children) {
                 node.children.push(arr)
               } else {
                 node['children'] = []
                 node.children.push(arr)
               }
             } else {
               if (node.children) {
                 setRouterList(node.children, item)
               }
             }
           })
         }

         function setData(list) {
           for (let i = 0; i < list.length; i++) {
             const e = list[i]
             let name = e.enCode.replace(/\./g, '-')
             let vueName = e.fullName.replace(/\./g, '.')
             e.vueName = vueName
             if (e.type == '01') {
               e.path = '/' + e.enCode.replace(/\./g, '/')
               if (e.children && e.children.length) {
                 setData(e.children)
               }
             }
             if (e.type == '02') {
               e.path = '/' + e.enCode.replace(/\./g, '/')
               let newObj = {
                 path: '/' + e.enCode.replace(/\./g, '/'),
                 component: (resolve) => require([`@/views${e.path}/index.vue`], resolve),
                 name: name,
                 meta: {
                   title: name,
                   icon: e.icon,
                   zhTitle: e.fullName,
                   modelId: e.id
                 }
               }
               routerList.push(newObj)
             }
           }
         }
         if (!menuList.length) {
           reject('您的权限不足，请联系管理员')
           return false;
         }
         setData(menuList)
         commit('SET_MENULIST', menuList)
         commit('SET_PERMISSION_LIST', permissionList)
         resolve(routerList)
       }).catch((res) => {
         // reject(res)
       })
       /*await GetBaseCodeString({
         // XB(性别),JLDW(计量单位),TMLX(题目类型),BPFS(编排方式),
         // CSLX(参数类型),CKGZ(参考规则),JGLB(机构类别),NJ(年级),
         // GNLX(功能类型),KSFS(考试方式),PFFS(评分方式),KSZT(考试状态),
         // XSKSZT(学生考试状态),FFZT(分发状态),HYLX(怀疑类型),JSDY(角色定义)
         Content: 'XB,CSLX,TMLX,BPFS,CKGZ,JGLB,NJ,GNLX,KSFS,PFFS,KSZT,XSKSZT,FFZT,HYLX,JSDY',
         Empty: false,
         All: false
       }).then(res => {
         console.log(res.Response, 'SET_BASE_CODE_STRING')
         commit('SET_BASE_CODE_STRING', res.Response)
       })*/
     })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      Logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_MENULIST', [])
        commit('SET_USERINFO', {})
        commit('SET_PERMISSION_LIST', [])
        // setHasToken(false)
        removeToken()
        setIsLogin(false)
        // resetRouter()
        removeUserInfo()
        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      })
    })
    /*return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_MENULIST', [])
      commit('SET_USERINFO', {})
      commit('SET_PERMISSION_LIST', [])
      setHasToken(false)
      removeToken()
      resetRouter()

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })*/
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      setHasToken(false)
      commit('SET_MENULIST', [])
      commit('SET_USERINFO', {})
      commit('SET_PERMISSION_LIST', [])
      commit('SET_LOGIN_LOADING', false)
      commit('SET_HAS_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
